package com.jinxin.platform.cdacsrecord.core.utils;

import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;

/**
 * Description: apcos-acs
 * Created by 34759 on 2020/4/22 15:59
 */
@Slf4j
public class ImageUtils {

    private static String ImageFormat="jpg";


    /**
     * 按照比例和规格压缩图片得到base64图片字符串
     * @param maxSize 单位kb
     * @param w
     * @param h
     * @return
     */
//    public static String resizeImage(String filePath,int maxSize,int w,int h){
//        try {
//            BufferedImage src = fileToBufferedImage(filePath);
//            BufferedImage output = Thumbnails.of(src).size(w, h).asBufferedImage();
//            String base64 = imageToBase64(output);
//            while (base64.length() - base64.length() / 8 * 2 > maxSize*1000) {
//                output = Thumbnails.of(output).scale(0.9f).asBufferedImage();
//                base64 = imageToBase64(output);
//            }
//            return imageToBase64(output);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }


    /**
     * 图片文件转BufferedImage
     * @param filePath
     * @return
     * @throws Exception
     */
    public static BufferedImage fileToBufferedImage(String filePath) throws Exception{
        FileInputStream is=new FileInputStream(filePath);
        BufferedImage img = ImageIO.read(is);
        return  img;
    }

    /**
     * 将图片base64字符串转换为BufferedImage  有问题读取后 image是空
     * @param base64string
     * @return
     */
//    public static BufferedImage base64String2BufferedImage(String base64string) {
//        BufferedImage image = null;
//        try {
//            InputStream stream = base64StringToInputStream(base64string);
//            image = ImageIO.read(stream);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return image;
//    }

    /**
     * 将base64字符转换为输入流
     * @param base64string
     * @return
     */
    public static InputStream base64StringToInputStream(String base64string) {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base64string.getBytes());
        InputStream inputStream=byteArrayInputStream;
        return inputStream;
    }

    /**
     * 将BufferedImage转换为base64字符串
     * @param bufferedImage
     * @return
     */
    public static String imageToBase64(BufferedImage bufferedImage) {
        Base64 encoder = new Base64();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, ImageFormat, baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(encoder.encode((baos.toByteArray())));
    }

    /**
          *通过图片base64流判断图片等于多少字节
          *image 图片流
          */
     public static Integer imageSize(String image){
        String str=image.substring(22); // 1.需要计算文件流大小，首先把头部的data:image/png;base64,（注意有逗号）去掉。
        Integer equalIndex= str.indexOf("=");//2.找到等号，把等号也去掉
        if(str.indexOf("=")>0) {
         str=str.substring(0, equalIndex);
        }
         Integer strLength=str.length();//3.原来的字符流大小，单位为字节
        Integer size=strLength-(strLength/8)*2;//4.计算后得到的文件流大小，单位为字节
         return size;
     }


    /**
     *
     * @param bytes 原图片字节数组
     * @param desFileSize 指定图片大小,单位 kb
     * @param accuracy 精度,递归压缩的比率,建议小于0.9
     * @return
     */
    public static byte[] commpressPicCycle(byte[] bytes, long desFileSize, double accuracy) throws IOException{
        // 获取目标图片
        long fileSize = bytes.length;
       log.info("=====fileSize======== "+fileSize);
        // 判断图片大小是否小于指定图片大小
        if(fileSize <= desFileSize * 1024){
            return bytes;
        }
        //计算宽高
        BufferedImage bim = ImageIO.read(new ByteArrayInputStream(bytes));
        int imgWidth = bim.getWidth();
        log.info(imgWidth+"====imgWidth=====");
        int imgHeight = bim.getHeight();
        int desWidth = new BigDecimal(imgWidth).multiply( new BigDecimal(accuracy)).intValue();
        log.info(desWidth+"====desWidth=====");
        int desHeight = new BigDecimal(imgHeight).multiply( new BigDecimal(accuracy)).intValue();
        ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流（写入到内存）
        Thumbnails.of(new ByteArrayInputStream(bytes)).size(desWidth, desHeight).outputQuality(accuracy).toOutputStream(baos);
        //如果不满足要求,递归直至满足要求
        return commpressPicCycle(baos.toByteArray(), desFileSize, accuracy);
    }


}
